//
//  SeachviewController.m
//  海角音乐
//
//  Created by dlios on 15-8-24.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SeachviewController.h"
#import "ReDetailModel.h"
#import "AFN.h"
#import "UIImageView+WebCache.h"
#import "ReDetailTableViewCell.h"

#import "MJRefresh.h"
#import "DanLiPlayer.h"
#import "MBProgressHUD.h"
#import "SinglePlayer.h"
@interface SeachviewController ()
{
    DanLiPlayer *BarPlayer;
    STKAudioPlayer *Legacy;
    UIImageView *back_image;
    UIImageView *kongkong;
    
}
@end

@implementation SeachviewController
-(void)dealloc{
    [_searchList release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _number = 1;
    _searchList = [[NSMutableArray alloc]init];
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"fanhui-3.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(left)];
    
    
    _searBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width , 60)];
    [[UISearchBar appearance]setBarTintColor:[UIColor blackColor]];
    _searBar.barTintColor = [UIColor redColor];

    [_searBar setBarStyle:UIBarStyleBlackOpaque];
    [_searBar setSearchBarStyle:UISearchBarStyleMinimal];
    [_searBar setShowsCancelButton:NO];
    _searBar.delegate = self;
    [self.view addSubview:_searBar];
    
    
    
    
     back_image=[[UIImageView alloc]initWithFrame:CGRectMake(0, 124, self.view.frame.size.width-10, self.view.frame.size.height - 94 )];
    [self.view addSubview:back_image];
    [back_image setUserInteractionEnabled:YES];
    
    kongkong = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    kongkong.center = CGPointMake(SCREEN_WIDTH/2, 200);
    kongkong.image = [UIImage imageNamed:@"content-empty.png"];
    [back_image addSubview:kongkong];


    _TableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width-10, self.view.frame.size.height - 94 ) style:UITableViewStylePlain];
    _TableView.backgroundColor = [UIColor clearColor];
    _TableView.separatorColor = [UIColor clearColor];
    [_TableView setDelegate:self];
    [_TableView setDataSource:self];
    [back_image addSubview:_TableView];
    
    
    BarPlayer = [DanLiPlayer shareHandleDanLiPlayer:CGRectZero];
    [self.view addSubview:BarPlayer];
    Legacy = [SinglePlayer shareHandleSinglePlayer];

}


-(void)left{
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _searchList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return SCREEN_WIDTH*0.2133333;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * flag = @"cellFlag";
    ReDetailTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:flag];
    if (!cell) {
        cell = [[ReDetailTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:flag];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellAccessoryNone;
        
    }
    if (_searchList.count > 0) {
        ReDetailModel *model = _searchList[indexPath.row];
        
        //cell.singer_name.text = model.singerName;
        cell.song_name.text = model.name;
        NSLog(@"11111");
        
        // 引入coretext 库
        
        //    关键字高亮
        
        NSString *str = model.singerName;
        //    NSLog(@"~~~~~~~~%@",str);
        
        //    初始化一个富文本属性
        NSMutableAttributedString *arrtiString = [[NSMutableAttributedString alloc]initWithString:str];
        
        //    搜索指定文字的范围
        NSRange range = [str rangeOfString:_searBar.text];
        
        //    给富文本添加属性
        [arrtiString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        
        cell.textLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row+1];
        cell.singer_name.attributedText = arrtiString;
        
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ReDetailModel *mo=[_searchList objectAtIndex:indexPath.row];
    
    BarPlayer.reDetailModel = mo;
    BarPlayer.dataArr = _searchList;
    BarPlayer.index = indexPath.row;
    [self playeMusicWithModel:mo index:indexPath.row];
    
}


- (void)playeMusicWithModel:(ReDetailModel *)model index:(NSInteger)index
{
    if (model.auditionList.count > 1) {
        NSDictionary *dic = [model.auditionList objectAtIndex:1];
        NSString *url_string = [dic objectForKey:@"url"];
        [Legacy play:url_string];
        
    } else {
        NSDictionary *dic = [model.auditionList objectAtIndex:0];
        NSString *url_string = [dic objectForKey:@"url"];
        [Legacy play:url_string];
    }
    
}




-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    [self searchData];
    [self newSearchData];
}

-(void)searchData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [_searchList removeAllObjects];
    NSString * searchString = _searBar.text;
    NSString *string = [NSString stringWithFormat:@"http://api.dongting.com/misc/search/song?s=s200&client_id=16debe5c39209afee3689dbf984c75fd&size=50&q=%@&v=v8.1.1.2015081120&imei=863583022034533&ram=1970220+kB&page=1&imsi=460026046186283&agent=none&longitude=0.0&hid=6125550060252570&net=2&app=ttpod&os=5.0.2&alf=alf700159&api_version=1.0&active=0&tid=0&latitude=0.0&f=f168&uid=863583022034533&user_id=0",searchString];
    string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    [AFN urlString:string getAFNdata:^(id responseObject) {
        
        
        if (responseObject == nil) {
            
            // 模拟加载延迟
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                HUD.mode = MBProgressHUDModeText;
                [HUD show:YES];
                [HUD hide:YES afterDelay:1];
                
                HUD.labelText = @"网络较差";
                [self.view addSubview:HUD];
                
            });
            
        } else {
            
            NSMutableArray *dataArray = [responseObject objectForKey:@"data"];
            if (dataArray.count == 0) {
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"没有匹配数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alert.delegate = self;
                [self.view addSubview:alert];
                [alert show];
                [alert release];
                
                 kongkong.hidden = NO;
                _TableView.separatorColor = [UIColor clearColor];
                [_TableView reloadData];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                
            } else {
               
                for (NSDictionary *myDic in dataArray) {
                    
                    
                    ReDetailModel *model = [[ReDetailModel alloc]init];
                    [model setValuesForKeysWithDictionary:myDic];
                    [_searchList addObject:model];
                    [model release];
                }
                
                kongkong.hidden = YES;
                _TableView.separatorColor = [UIColor lightGrayColor];
                [_TableView reloadData];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }

                
            }
            
    }];
    
}

-(void)newSearchData{
    [_TableView addFooterWithCallback:^{
        _number ++;
        NSString * searchString = _searBar.text;
        NSString *string = [NSString stringWithFormat:@"http://api.dongting.com/misc/search/song?s=s200&client_id=16debe5c39209afee3689dbf984c75fd&size=50&q=%ld&cpu=msm8960&v=v8.1.1.2015081120&imei=863583022034533&ram=1970220+kB&page=%ld&imsi=460026046186283&agent=none&longitude=0.0&hid=6125550060252570&net=2&app=ttpod&os=5.0.2&alf=alf700159&api_version=1.0&active=0&tid=0&latitude=0.0&f=f168&uid=863583022034533&user_id=0",(long)searchString,_number];
        string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        
        
        [AFN urlString:string getAFNdata:^(id responseObject) {
            
            NSMutableArray *dataArray = [responseObject objectForKey:@"data"];
            for (NSDictionary *myDic in dataArray) {
                ReDetailModel *model = [[ReDetailModel alloc]init];
                [model setValuesForKeysWithDictionary:myDic];
                NSArray *auditionListArray = [myDic objectForKey:@"auditionList"];
                if (auditionListArray.count > 1) {
                    NSDictionary *dd = auditionListArray[1];
                    [model setValuesForKeysWithDictionary:dd];
                }else{
                    NSDictionary *dd = auditionListArray[0];
                    [model setValuesForKeysWithDictionary:dd];
                }
                [_searchList addObject:model];
                [model release];
            }
            [_TableView reloadData];
        }];
        [_TableView footerEndRefreshing];
    }];
}





-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
